#include "httpmanager.h"
#include <QJsonDocument>
HttpManager::HttpManager()
{
    connect(this, &HttpManager::sig_http_finish, this, &HttpManager::slot_http_finish);
}

void HttpManager::PostHttpReq(QUrl url, QJsonObject &json, ReqId id, Modules mod)
{
    QByteArray data = QJsonDocument(json).toJson(QJsonDocument::Compact);
    QNetworkRequest request(url);
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    request.setHeader(QNetworkRequest::ContentLengthHeader, QByteArray::number(data.length()));
    auto self = shared_from_this();
    QNetworkReply *reply = _manager.post(request, data);
    connect(reply, &QNetworkReply::finished, this, [self, reply, id, mod]() {
        // 错误处理
        if (reply->error() != QNetworkReply::NoError) {
            qDebug() << "QNetworkReply error is " << reply->errorString() << "\n";
            // 发送信号通知完成
            emit self->sig_http_finish(id, "", ErrorCode::ERROR_NETWORK, mod);
            reply->deleteLater();
            return;
        }
        // 无错误
        QString res = reply->readAll();
        // 发送信号通知完成
        emit self->sig_http_finish(id, res, ErrorCode::SUCCESS, mod);
        reply->deleteLater();
        return;
    });
}

void HttpManager::slot_http_finish(ReqId id, QString res, ErrorCode ec, Modules mod)
{
    // 发送信号通知相应模块http响应结束了
    switch (mod) {
    case Modules::REGISTERMOD:
        emit sig_reg_mod_finish(id, res, ec);
        break;
    case Modules::RESETPWDMOD:
        emit sig_reset_mod_finish(id, res, ec);
        break;
    case Modules::LOGINDMOD:
        emit sig_login_mod_finish(id, res, ec);
        break;
    default:
        qDebug() << "(HttpManager) 未注册模块：" << mod;
        break;
    }
}

HttpManager::~HttpManager() {}
